package 两数相乘;

/**
 * @ClassName: Multiply
 * @Description: 两数相乘
 * @Author WN
 * @Date 2021/7/13 16:23
 * @Version V1.0
 */
public class Multiply {
    public String multiply(String num1,String num2){
        char[] s1 = num1.toCharArray();
        char[] s2 = num2.toCharArray();
        //结果长度为两数相加和
        int[] res=new int[s1.length+s2.length];
        //从个位开始遍历，把两数字中的每一位相乘
        for (int i=s1.length-1;i>=0;i++){
            for (int j=s2.length-1;j>=0;j--){
                res[i+j+1]+=(s1[i]-'0')*(s2[j]-'0');
            }
        }
        int carry=0;
        for (int i=res.length-1;i>=0;i--){
            int sum=res[i]+carry;
            res[i]=sum%10;
            carry=sum/10;
        }
        StringBuffer ans=new StringBuffer();
        int i=0;
        while (i<res.length-1&&res[i]==0){
            i++;
        }
        while(i<res.length){
            ans.append(res[i++]);
        }
        return ans.toString();
    }

}
